import React, { useState, useCallback } from "react";
import { Button, Input, Modal, Radio, Form, Row, Col, message, Tag, TreeSelect, Divider, Tooltip } from "antd";
import {
    CopyOutlined,
    LockOutlined,
    UnlockOutlined,
    FolderOutlined,
    FolderOpenOutlined
} from "@ant-design/icons";
import { uuid } from "../../../common/utils/createId";
import md5 from "js-md5";
import categoryStore from "../../../category/store/CategoryStore";
import shareStore from "../store/ShareStore";
import {TextMethodType} from "../../../common/MethodType";
import "./shareStyle.scss"
import IconCommon from "../../../common/IconCommon";

/**
 * 创建分享组件
 * 实现一个可以选择分享项目、目录或接口的弹窗界面
 * 支持多选节点分享
 */
const CreateShare = (props) => {
    const { findPage,btn } = props
    const { findNodeTree, categoryList } = categoryStore;
    const { createShare } = shareStore;

    // 控制弹窗显示状态
    const [visible, setVisible] = useState(false);
    // 存储多选的节点IDs
    const [nodeIds, setNodeIds] = useState([]);
    // 分享目标类型：workspace-项目, custom-自定义(包含目录和接口)
    const [targetType, setTargetType] = useState("workspace");
    // 分享可见性：0-公开, 1-密码访问
    const [visibility, setVisibility] = useState(0);
    // 密码
    const [password, setPassword] = useState("");
    // 表单实例
    const [form] = Form.useForm();
    // 生成的分享链接
    const [shareUrl, setShareUrl] = useState("");

    // 工作区ID
    const workspaceId = localStorage.getItem("workspaceId");

    // 目标类型映射表（显示用）
    const TARGET_TYPE_MAP = {
        custom: "自定义",
        workspace: "项目"
    };

    // 加载分类树
    const findTree = useCallback(async () => {
        await findNodeTree({ workspaceId });
    }, [findNodeTree, workspaceId]);

    /**
     * 根据节点类型获取对应图标
     * @param {Object} node - 节点数据
     * @param {boolean} expanded - 节点是否展开
     * @returns {React.ReactNode}
     */
    const getNodeIcon = (node, expanded) => {
        const { type, methodType } = node;

        if (type === 'category') {
            // return expanded ? <FolderOpenOutlined /> : <FolderOutlined />;
        } else if (type === 'ws') {
            return <span style={{ color: "#0070ff" }} className={"requestType"}>{type.toUpperCase()}</span>;
        } else if (type === 'http') {
            try {
                return <TextMethodType type={methodType} />;
            } catch (e) {
                return <span>{methodType || 'HTTP'}</span>;
            }
        }

        // 默认图标
        return <FolderOutlined />;
    };

    /**
     * 自定义树节点的渲染
     * @param {Object} nodeData - 节点数据
     * @returns {Object} 增强后的节点数据
     */
    const enhanceTreeData = useCallback((data) => {
        return data.map(node => {
            const enhanced = {
                ...node,
                icon: (props) => getNodeIcon(node, props.expanded)
            };

            if (node.children && node.children.length > 0) {
                enhanced.children = enhanceTreeData(node.children);
            }

            return enhanced;
        });
    }, []);

    // 增强的分类树数据
    const enhancedCategoryList = enhanceTreeData(categoryList || []);

    /**
     * 显示创建分享弹窗
     */
    const showModal = async () => {
        setVisible(true);
        form.resetFields();
        setShareUrl("");
        setNodeIds([]);
        // 默认生成一个密码，以备用户选择密码访问
        setPassword(uuid(6));

        await findTree();
    };

    /**
     * 关闭弹窗
     */
    const handleCancel = () => {
        setVisible(false);
    };

    /**
     * 处理分享目标类型变化
     * @param {Event} e - 事件对象
     */
    const handleTargetTypeChange = (e) => {
        const type = e.target.value;
        setTargetType(type);

        // 重置表单中的选择
        if (type === "workspace") {
            setNodeIds([]);
        }
        form.setFieldsValue({ nodeIds: undefined });
    };

    /**
     * 处理分享可见性变化
     * @param {Event} e - 事件对象
     */
    const handleVisibilityChange = (e) => {
        const type = e.target.value;
        setVisibility(type);

        if (type === 0) {
            // 公开访问，清空密码
            form.setFieldsValue({ password: undefined });
        } else {
            // 密码访问，设置默认密码
            form.setFieldsValue({ password });
        }
    };

    /**
     * 处理TreeSelect的选择变化
     * @param {Array} selectedIds - 选中的节点IDs
     */
    const handleNodeIdsChange = (selectedIds) => {
        console.log("selectedIds:", selectedIds);
        setNodeIds(selectedIds);
        form.setFieldsValue({ nodeIds: selectedIds });
    };

    /**
     * 创建分享
     */
    const handleCreate = async () => {
        try {
            const values = await form.validateFields();

            // 生成唯一标识符作为分享码
            const timestamp = new Date().getTime();
            const code = md5(`${workspaceId}_${timestamp}`);

            const shareParam = {
                name: values.name || "未命名",
                code,
                workspaceId,
                targetType,
                visibility,
                password: visibility === 1 ? values.password : null,
            };

            // 根据目标类型设置不同的参数
            if (targetType === "workspace") {
                // 项目分享，直接使用工作区ID
                shareParam.targetId = workspaceId;
                shareParam.nodeIds = null;
            } else {
                // 自定义分享，使用选中的节点IDs
                shareParam.targetId = null;
                shareParam.nodeIds = nodeIds;
            }

            await createShare(shareParam);
            findPage&&findPage()
            message.success("分享创建成功");
        } catch (error) {
            console.error("创建分享失败:", error);
            message.error("分享创建失败");
        }

        setVisible(false);
    };

    /**
     * 复制分享链接
     */
    const copyShareLink = () => {
        if (shareUrl) {
            navigator.clipboard.writeText(shareUrl)
                .then(() => {
                    message.success("链接已复制到剪贴板");
                })
                .catch(() => {
                    message.error("复制失败，请手动复制");
                });
        }
    };

    /**
     * 渲染当前选择的目标类型标签
     */
    const renderTargetTypeTag = () => {
        const colorMap = {
            workspace: "blue",
            custom: "purple"
        };

        return (
            <Tag color={colorMap[targetType] || "blue"}>
                {TARGET_TYPE_MAP[targetType] || targetType}
            </Tag>
        );
    };

    /**
     * 渲染已选节点的数量标签（仅适用于自定义模式）
     */
    const renderSelectedNodesTag = () => {
        if (targetType === "custom" && nodeIds.length > 0) {
            return (
                <Tag color="green">已选择 {nodeIds.length} 个节点</Tag>
            );
        }
        return null;
    };

    /**
     * 自定义多选标签的显示
     * @param {Array} omittedValues - 被省略的值
     * @returns {React.ReactNode}
     */
    const customMaxTagPlaceholder = (omittedValues) => {
        return (
            <Tooltip
                title={`${omittedValues.length}个已选节点`}
                placement="top"
            >
                <Tag color="blue">+{omittedValues.length}...</Tag>
            </Tooltip>
        );
    };

    const renderBtn = () => {
        if (btn){
            return (
                <Button type="primary" onClick={showModal}>
                    创建分享
                </Button>
            );
        }

        return <a  onClick={showModal} className={"display-flex-gap-5"}>
                    <IconCommon
                        icon="fenxiang"
                        className="icon-s"
                        onClick={showModal}
                    />
                    分享
                </a>;
    };

    return (
        <>
            {renderBtn()}
            <Modal
                title="创建分享链接"
                open={visible}
                onCancel={handleCancel}
                footer={null}
                destroyOnClose={true}
                width={600}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        targetType: "workspace",
                        visibility: 0
                    }}
                >
                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{ required: visibility === 1, message: "请输入分享名称" }]}
                    >
                        <Input
                            placeholder="分享名称"
                            style={{ width: "100%" }}
                            maxLength={20}
                        />
                    </Form.Item>

                    <Form.Item label="分享类型" name="targetType">
                        <Radio.Group
                            value={targetType}
                            onChange={handleTargetTypeChange}
                            optionType="button"
                            buttonStyle="solid"
                            style={{ marginBottom: 16 }}
                        >
                            <Radio.Button value="workspace">项目</Radio.Button>
                            <Radio.Button value="custom">自定义</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    {targetType === "custom" && (
                        <Form.Item
                            name="nodeIds"
                            label="选择要分享的节点"
                            rules={[{ required: true, message: "请至少选择一个节点" }]}
                        >
                            <TreeSelect
                                treeCheckable={true}
                                style={{ width: "100%" }}
                                treeData={enhancedCategoryList}
                                placeholder="请选择要分享的节点(可多选)"
                                treeNodeFilterProp="name"
                                value={nodeIds}
                                onChange={handleNodeIdsChange}
                                showCheckedStrategy={TreeSelect.SHOW_PARENT}
                                fieldNames={{
                                    label: "name",
                                    value: "id",
                                    children: "children"
                                }}
                                maxTagCount={3}
                                maxTagPlaceholder={customMaxTagPlaceholder}
                                maxTagTextLength={10}
                                listHeight={300}
                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                // treeIcon={true}
                                treeNodeLabelProp="name"
                                popupClassName={"custom-dropdown"}
                            />
                        </Form.Item>
                    )}

                    <Form.Item label="访问方式" name="visibility">
                        <Radio.Group
                            value={visibility}
                            onChange={handleVisibilityChange}
                            optionType="button"
                            buttonStyle="solid"
                            style={{ marginBottom: 16 }}
                        >
                            <Radio.Button value={0}><UnlockOutlined /> 公开访问</Radio.Button>
                            <Radio.Button value={1}><LockOutlined /> 密码访问</Radio.Button>
                        </Radio.Group>

                        {visibility === 0 && (
                            <div className="share-tip" style={{ color: "#999" }}>
                                创建后任何获得链接的人都能查看
                            </div>
                        )}

                        {visibility === 1 && (
                            <Form.Item
                                name="password"
                                rules={[{ required: visibility === 1, message: "请设置访问密码" }]}
                                initialValue={password}
                            >
                                <Input.Password
                                    placeholder="请设置访问密码"
                                    style={{ width: "100%" }}
                                    maxLength={20}
                                />
                            </Form.Item>
                        )}
                    </Form.Item>

                    <Divider />

                    {/*{shareUrl && (*/}
                    {/*    <Row className="share-link-container" style={{ marginBottom: 16 }}>*/}
                    {/*        <Col span={3}>已创建:</Col>*/}
                    {/*        <Col span={21}>*/}
                    {/*            {renderTargetTypeTag()}*/}
                    {/*            {renderSelectedNodesTag()}*/}
                    {/*        </Col>*/}

                    {/*        <Col span={3} style={{ marginTop: 16 }}>链接:</Col>*/}
                    {/*        <Col span={17} style={{ marginTop: 16 }}>*/}
                    {/*            <Input*/}
                    {/*                value={shareUrl}*/}
                    {/*                readOnly*/}
                    {/*            />*/}
                    {/*        </Col>*/}
                    {/*        <Col span={4} style={{ marginTop: 16, textAlign: "center" }}>*/}
                    {/*            <Button*/}
                    {/*                type="primary"*/}
                    {/*                icon={<CopyOutlined />}*/}
                    {/*                onClick={copyShareLink}*/}
                    {/*                style={{ marginLeft: 8 }}*/}
                    {/*            >*/}
                    {/*                复制*/}
                    {/*            </Button>*/}
                    {/*        </Col>*/}
                    {/*    </Row>*/}
                    {/*)}*/}

                    {/* 根据shareUrl状态决定是否显示按钮 */}
                    {!shareUrl && (
                        <Row justify="end" gutter={16} style={{ marginTop: 24 }}>
                            <Col>
                                <Button onClick={handleCancel}>取消</Button>
                            </Col>
                            <Col>
                                <Button
                                    type="primary"
                                    onClick={handleCreate}
                                    disabled={(targetType === "custom" && nodeIds.length === 0)}
                                >
                                    创建分享
                                </Button>
                            </Col>
                        </Row>
                    )}
                </Form>
            </Modal>
        </>
    );
};

export default CreateShare;